package com.wswy.wzcx.module.base

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProviders
import android.os.Bundle
import android.support.annotation.Keep
import android.support.v4.util.SparseArrayCompat
import android.view.View
import android.widget.TextView
import com.che.libcommon.ui.BaseActivity
import com.wswy.wzcx.R
import com.wswy.wzcx.model.core.EventNormal
import com.wswy.wzcx.statistics.StatTools
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class CBaseActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        if (!EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().register(this)
        }

    }

    protected fun <T: ViewModel> provideViewModel(modelClass:Class<T>):T{
        return ViewModelProviders.of(this).get(modelClass)
    }

    protected val tvTitle:TextView? by lazy {
        findViewById<View>(R.id.img_back)?.let {
            it.setOnClickListener {
                onClickBack(it)
            }
        }?:kotlin.run {
            findViewById<View>(R.id.img_close)?.let {
                it.setOnClickListener {
                    onClickBack(it)
                }
            }
        }


        findViewById<TextView>(R.id.tv_title)
    }


    protected fun setAppTitle(title:CharSequence?){
        tvTitle?.text = title
    }

    protected open fun onClickBack(view:View){
        finish()
    }

    inline fun sendClickEvent(id:String){
        StatTools.sendClick(applicationContext, id)
    }


    private lateinit var events : SparseArrayCompat<((Any?) -> Unit)>

    @Keep
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventCodeNormal(event: EventNormal){
        if(this::events.isInitialized){
            events.get(event.code)?.invoke(event.code)
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        if (EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

    fun registerEvent(code:Int,callback:((Any?)->Unit)?){
        if (!this::events.isInitialized){
            events = SparseArrayCompat()
        }
        events.put(code,callback)
    }

}